﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Xml;

namespace LiveNet.Contacts
{
    public class ContactCollection
    {
        #region Private Data
        private ArrayList contacts = new ArrayList();
        #endregion

        #region Constructors
        internal ContactCollection()
        {
        }

        internal ContactCollection(XmlNode xmlnode)
        {
            FromXml(xmlnode);
        }
        #endregion

        #region Public Methods
        public XmlDocument ToXml(OperationType op)
        {
            XmlDocument xmldoc = new XmlDocument();
            string xml = "<Contacts>";
            foreach (Contact contact in contacts)
            {
                xml = xml + contact.ToXml(op).InnerXml;
            }
            xml = xml + "</Contacts>";
            xmldoc.LoadXml(xml);

            return xmldoc;
        }

        public Contact New()
        {
            return new Contact();
        }

        public IEnumerator GetEnumerator()
        {
            return contacts.GetEnumerator();
        }

        public Contact Find(Guid contactID)
        {
            foreach (Contact contact in contacts)
            {
                if (contact.ID == contactID) return contact;
            }
            return null;
        }
        #endregion

        #region Internal Methods
        internal void FromXml(XmlNode xmlnode)
        {
            if (xmlnode == null) return;

            XmlNodeList nodes = xmlnode.SelectNodes("Contact");
            if (nodes != null)
            {
                foreach (XmlNode node in nodes)
                {
                    Add(new Contact(node));
                }
            }
        }

        internal Contact New(XmlDocument xmlDoc)
        {
            return new Contact(xmlDoc);
        }

        internal void Add(Contact contact)
        {
            contacts.Add(contact);
        }

        internal void Remove(Contact contact)
        {
            contacts.Remove(contact);
        }

        internal void RemoveAll()
        {
            contacts.Clear();
        }
        #endregion

        #region Public Properties
        public int Count
        {
            get { return contacts.Count; }
        }

        public object[] ToArray
        {
            get { return contacts.ToArray(); }
        }
        #endregion
    }
}
